package com.chatplus.application.config.ws;

import com.chatplus.application.aiprocessor.handler.ChatWebSocketHandler;
import com.chatplus.application.aiprocessor.handler.MJWebSocketHandler;
import com.chatplus.application.aiprocessor.handler.SdWebSocketHandler;
import com.chatplus.application.config.ws.interceptor.PlusWebSocketInterceptor;
import com.chatplus.application.domain.request.ws.ChatWebSocketRequest;
import io.micrometer.core.lang.Nullable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * websocket配置
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final ChatWebSocketHandler chatWebSocketHandler;
    private final MJWebSocketHandler mjWebSocketHandler;

    private final SdWebSocketHandler sdWebSocketHandler;
    private final PlusWebSocketInterceptor plusWebSocketInterceptor;

    public WebSocketConfig(ChatWebSocketHandler chatWebSocketHandler
            , PlusWebSocketInterceptor plusWebSocketInterceptor,
                           MJWebSocketHandler mjWebSocketHandler,
                           SdWebSocketHandler sdWebSocketHandler) {
        this.chatWebSocketHandler = chatWebSocketHandler;
        this.plusWebSocketInterceptor = plusWebSocketInterceptor;
        this.mjWebSocketHandler = mjWebSocketHandler;
        this.sdWebSocketHandler = sdWebSocketHandler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                .addHandler(chatWebSocketHandler, ChatWebSocketRequest.WS_URL_PATH)
                .addHandler(mjWebSocketHandler, ChatWebSocketRequest.MJ_URL_PATH)
                .addHandler(sdWebSocketHandler, ChatWebSocketRequest.SD_URL_PATH)
                .addInterceptors(plusWebSocketInterceptor) // 添加拦截器，预处理
                .setAllowedOrigins("*"); // 解决跨域问题
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    // 解决spring中socketBean冲突，如果有冲突就加没有就不管
    @Bean
    @Nullable
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
        threadPoolScheduler.setThreadNamePrefix("SockJS-");
        threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        threadPoolScheduler.setRemoveOnCancelPolicy(true);
        return threadPoolScheduler;
    }
}
